import React, {PureComponent} from 'react';
import {connect} from 'dva'
import {routerRedux} from 'dva/router'
import {
    Row,
    Col,
    Card,
    Form,
    Select,
    Button,
    message,
    Modal,
} from 'antd';
import PageHeaderLayout from "../../../layouts/PageHeaderLayout";
import RecObjectList from "../../../components/Operation/RecObject/RecObjectList"
import RecObjectAdd from "../../../components/Operation/RecObject/RecObjectAdd";
import styles from './RecObject.less';
import {powerControl} from '../../../utils/powerControl';
const AuthButton = powerControl(Button);

const FormItem = Form.Item;
const {Option}=Select;
@connect(state => ({
    rule: state.recObject
}))
@Form.create()
export default class RecObject extends PureComponent{
    state = {
        modalVisible: false,
        recObjectVisible:false,
        editType: 'add',
        record: {},
        selectedRows: [],
        formValues: {},
        adConfigruation: [],
        adAddress: [],
    };

    componentDidMount(){
        const {dispatch} = this.props;
        dispatch({
           type: 'recObject/fetch'
        });
        dispatch({
            type: 'adConfigruation/queryAllAdConfigruation' ,
            callback: (response) => {
                if (response.result === 0) {
                    this.setState({
                        adConfigruation: response.resultData.adConfigruationList,
                    })
                    console.log(this.state.adConfigruation);
                }
            }
        });
        dispatch({
            type: 'adAddress/queryAllYyDetailUrl',
            callback: (response) => {
                if (response.result === 0) {
                    this.setState({
                        adAddress: response.resultData.yyDetailUrlList
                    })
                    console.log(this.state.adAddress);
                }
            }
        });
    };

    /**
     * 改变modal状态
     * @param flag
     */
    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    /**
     * 查询
     */
    search = (e) =>{
        e.preventDefault();

        const {dispatch, form} = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err){
                return;
            }
            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };

            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'recObject/fetch',
                payload: values,
            })
        });
    };

    /**
     * form重置
     * @constructor
     */
    FormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        dispatch({
            type: 'recObject/fetch',
            payload: {},
        });
        this.setState({
            formValues: {},
        })
    };

    /**
     * 跳转到品牌页面
     * @constructor
     */
    IntentBrand = () => {
        const {dispatch} = this.props;
        dispatch(routerRedux.push('/goods/brand'));
    };

    /**
     * 跳转到分类页面
     * @constructor
     */
    IntentCategary = () => {
        const {dispatch} = this.props;
        dispatch(routerRedux.push('/goods/category'));
    };

    /**
     * 跳转到商品页面
     * @constructor
     */
    IntentGoods = () => {
        const {dispatch} = this.props;
        dispatch(routerRedux.push('/goods/goodsManage'));
    };

    /**
     * 删除列表行
     * @param priority_id
     * @param pagination
     */
    handleDelRecObject = (priority_id, pagination) =>{
        const {dispatch} = this.props;
        dispatch({
            type: 'recObject/del',
            payload: {priority_id: priority_id},
            callback: (response) => {
                 console.log("wwww", priority_id);
                if (response.result === 0){
                    message.success('删除成功');
                    this.handleModalSuccess(pagination);
                }else {
                    message.success('删除失败');
                }
            }
        })
    };

    /**
     * 编辑列表行
     * @param record
     * @param pagination
     */
    handleEditRecObject = (record) => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'mod',
            record: record,
        })
    };

    handleSelectRows = (row) =>{
        this.setState({
            selectedRows: row,
        });
    };

    /**
     * 翻页
     * @param pagination
     * @param filtersArg
     * @param sorter
     */
    handleRecObjectListChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formVales} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) =>{
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formVales,
            ...filters,
        };

        if (sorter.field){
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'recObject/fetch',
            payload: params,
        });
    };

    /**
     * 新增成功重新查询列表
     * @param pagination
     */
    handleModalSuccess = (pagination) =>{
        const {dispatch} = this.props;
        const {formValues} = this.state;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
        };
        dispatch({
            type: 'recObject/fetch',
            payload: params,
        })

    };

    /**
     * 修改推荐对象
     */
    handleModalSubmit =()=>{
        this.props.dispatch({
            type: 'recObject/add',
            payload: {
                description: this.state.addInputValue,
            }
        });
    };

    /**
     * 表单验证查询栏
     */
    renderForm(){
        const {getFieldDecorator} = this.props.form;
        const {adConfigruation, adAddress} = this.state;
        const optionsAdConfigruation = adConfigruation.map(d => <Option value={d.value}>{d.label}</Option>)
        const optionAdAddress = adAddress.map(d => <Option value={d.value} >{d.label}</Option>)
        return(
            <Form layout="inline" onSubmit={this.search}>
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={10} sm={24}>
                        <FormItem label="位置编码-位置名称">
                            {getFieldDecorator('seat_id')(
                                <Select placeholder="请选择" style={{width: '100%'} }>
                                    {optionsAdConfigruation}
                                </Select>
                            )}
                        </FormItem>
                    </Col>

                    <Col md={6} sm={24}>
                        <FormItem label="转入地址">
                            {getFieldDecorator('du_id')(
                                <Select placeholder="请选择" style={{width: '100%'} }>
                                    {optionAdAddress}
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={5} sm={24}>
                        <span className={styles.sumbitButtons}>
                            <AuthButton auth="recObject.search" type="primary" htmlType="submit">
                                查询
                            </AuthButton>
                            <AuthButton auth="recObject.reset" style={{marginLeft: 8}} onClick={this.FormReset}>
                                重置
                            </AuthButton>
                        </span>
                    </Col>
                </Row>
            </Form>
        )
    }
    /**
     * 修改是否显示自定义推荐模态框的
     * @param flag
     */
    handlerecObjectVisible = (flag) => {
        this.setState({
            recObjectVisible: !!flag,
            editType:'add'
        })
    };
    /**
     * 推荐对象新增提交
     */
    handleRecObjectAdd = () => {
        // this.props.dispatch({
        //     type: 'recObject/add',
        //     payload: {
        //         description: this.state.addInputValue,
        //     },
        // });
        message.success('添加成功');
        this.setState({
            recObjectVisible: false,
        });
        dispatch({
            type: 'recObject/fetch'
        });
    }
    render(){
        const {modalVisible,recObjectVisible, editType, record, selectedRows}=this.state;
        const {rule: {loading: ruleLoading, data, recObjectList}} = this.props;
        return(
            <PageHeaderLayout title="推荐对象">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <div className={styles.tableListOperator} style={{marginTop: 8}}>
                            <AuthButton auth="recObject.brandcommend" type="primary" icon = "link" onClick={this.IntentBrand}>
                                品牌推荐
                            </AuthButton>

                            <AuthButton auth="recObject.goodscommend" style={{marginLeft: 8, marginBottom: 20}} type="primary" icon="link" onClick={this.IntentGoods}>
                                商品推荐
                            </AuthButton>
                            <AuthButton auth="recObject.diycommend" style={{marginLeft: 8, marginBottom: 20}} type="primary" icon="link" onClick={this.IntentCategary}>
                                分类推荐
                            </AuthButton>
                            <AuthButton auth="recObject.diycommend" style={{marginLeft: 8, marginBottom: 20}} type="primary" icon="link" onClick={()=>this.handlerecObjectVisible(true)}>
                                自定义推荐
                            </AuthButton>

                            <RecObjectList
                                selectedRows={selectedRows}
                                loading={ruleLoading}
                                data={data}
                                onDelRow={this.handleDelRecObject}
                                onEditRow={this.handleEditRecObject}
                                onSelectRow={this.handleSelectRows}
                                onChange={this.handleRecObjectListChange}
                            />
                        </div>
                    </div>
                </Card>

                <Modal
                    title="修改推荐对象"
                    visible={modalVisible}
                    onOk={this.handleModalSubmit}
                    onCancel={()=>this.handleModalVisible()}
                    footer={null}
                    width={700}
                    key={new Date()}
                >
                    <RecObjectAdd
                        editType={editType}
                        pagination = {data.pagination}
                        record={record}
                        recObjectList={recObjectList}
                        handlerecObjectVisible={this.handleModalVisible}
                        handleModalSuccess={this.handleModalSuccess}
                    />
                </Modal>
                <Modal
                    title="自定义推荐对象"
                    key={new Date() + 1}
                    width={700}
                    visible={recObjectVisible}
                    onOk={this.handleRecObjectAdd}
                    onCancel={() => this.handlerecObjectVisible()}
                    footer={null}
                >
                    <RecObjectAdd  ref="recObjectAdd"
                                   pagination={data.pagination}
                                   editType={editType}
                                   record={record}
                                   type={3}
                                   handlerecObjectVisible={this.handlerecObjectVisible}
                                   returnRecObject={this.returnRecObject}
                    />
                </Modal>
            </PageHeaderLayout>
        )
    }
}